package com.easy.leetcode.listNode;

import com.easy.leetcode.ListNode;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * @ClassName MergeKLists23
 * @Description TODO
 * @Author zheng
 * @Date 2021/10/26 20:03
 * @Version 1.0
 **/
public class MergeKLists23 {
    public ListNode mergeKLists(ListNode[] lists) {
        //创建头节点
        ListNode head = new ListNode(Integer.MIN_VALUE);
        for (ListNode listNode : lists) {
            head = mergeTwoLists(head, listNode);
        }
        return head.next;
    }

    private ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null || l2 == null) {
            return l1 == null ? l2 : l1;
        }
        ListNode head = new ListNode(-1);
        ListNode tmp = head;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                tmp.next = l1;
                l1 = l1.next;
            } else {
                tmp.next = l2;
                l2 = l2.next;
            }
            tmp = tmp.next;
        }
        if (l1 == null) {
            tmp.next = l2;
        }
        if (l2 == null) {
            tmp.next = l1;
        }
        return head.next;
    }

}
